import logging
import os

from ronglian_sms_sdk import SmsSDK

logger = logging.getLogger("django")


class RongLianSMS:
    DEFAULT_TiD = "1"
    _instance = None
    _initialized = False

    def __new__(cls):

        if cls._instance is None:
            cls._instance = super().__new__(cls)

        return cls._instance

    def __init__(self):

        # 防止重复初始化
        if self._initialized:
            return

        self.accId = os.getenv("RL_SMS_ACCID", "2c94811c9787a27f01985e7e1f7b2e17")
        self.accToken = os.getenv("RL_SMS_ACCTOKEN", "43afb1d374a042998dc1bd77bb2805ee")
        self.appId = os.getenv("RL_SMS_APPID", "2c94811c9787a27f01985e7e21482e1e")
        self.sdk = SmsSDK(self.accId, self.accToken, self.appId)

        self.__class__.initialized = True

    def send_sms(self, mobile, code, minute=5):
        try:
            datas = (code, str(minute))
            resp = self.sdk.sendMessage(self.DEFAULT_TiD, mobile, datas)
            return resp
        except Exception as e:
            logger.error(f"发送给{mobile}短信失败， 错误信息: {e}")
            return {
                "statusCode": "-1",
                "statusMsg": f"发送短信失败：{e}"
            }
